<!--
/**
 * Eva Javascript Core File
 * Mapping Zend Framework RESTFul resource to Javascript functions
 * UI depends on jQuery, jQuery UI, Tinymce, LabJs
 *
 *
 * @author     XuQian(AlloVince) <xuqian@easthv.com>
 * @copyright  2011 AlloVince
 * @version    1.10
 */
(function(){

var 

window = this,

undefined ,

//web dir
d = function(dir) {
	return dir === undefined ? eva.config.dir : eva.config.dir + dir;
},

s = function(dir){
	return dir === undefined ? eva.config.s : eva.config.s + dir;
},

f = function(dir){
	return dir === undefined ? eva.config.f : eva.config.f + dir;
},

p = function (m){
	if(typeof console === 'undefined')
		return alert(m);
	return console.log(m);
},


eva = window.eva = {

	config : {
		debug : true,
		params : {},
		login : false,
		username : false,
		lang : "en",
		dir : "",
		f : "",
		s : '',
		ie : false
	},

	p : function (m){
		return p(m);
	},

	d : function(dir) {
		return d(dir);
	},

	s : function(dir){
		return s(dir);
	},

	f : function(dir){
		return f(dir);
	},

	//do sth before load Jquery
	init : function(setting){
		eva.config = eva.initConfig(eva.config,setting);
		var func = eva.initRouter();

		jQuery(document).ready(function () {

			if(eva.construct !== undefined) {
				eva.construct();
			}

			var func = eva.initRouter();
			func();


			if(eva.destruct !== undefined) {
				eva.destruct();
			}

			return false;
		});

	},

	debug : {
		showGrid : function(){
			jQuery(window).load(function(){
				var width = 950;
				var margin_left = 0 - width / 2;
				jQuery("body").append('<div id="grid" style="position:absolute;margin-left:' + margin_left + 'px;top:0;left:50%;width:' + width + 'px;height:' + jQuery("#page").height() + 'px;background:#CCC url(' + s('/skins/grid950.png') + ') repeat top left;z-index:9999;"></div>');
				jQuery("#grid").animate({opacity:0.5},0).click(function(){
					jQuery(this).hide();		
				});				
			});
		}		
	},

	module : {},

	initConfig : function(config, setting){
		var i;
		for(i in setting) {
			config[i] = setting[i];
		}
		return config;
	},

	initRouter : function(){
		if(!eva.config.params) {
			return;
		}
		var func = eva.getRouterName();
		var module = eva.config.params.module;
		
		if(module === undefined || module == 'default') {
			return eva[func] === undefined ? function(){} : eva[func];
		} else {
			var modulefunc = module.charAt(0).toUpperCase() + module.substr(1) + '_' + func;
			
			return eva.module[modulefunc] === undefined ? 
				( eva[func] === undefined ? function(){} : eva[func] )
				: eva.module[modulefunc];
		}
		
	},

	getRouterName : function(){
		return eva.config.params.action + eva.config.params.resource;
	},

	trim : function(str){
		if(!String.prototype.trim){
			return str.replace(/^\s+|\s+$/g, '');
		}
	},

	preload : function() { 
		var cache = [];
		var args_len = arguments.length;
		for (var i = args_len; i--;) {
			var cacheImage = document.createElement('img');
			cacheImage.src = arguments[i];
			cache.push(cacheImage);
		}
	},

	loadcss : function() {
		var len = arguments.length;
		var head = document.getElementsByTagName("head")[0];
		var css = document.createElement('link');
		css.type = 'text/css';
		css.rel = "stylesheet";
		for(var i = 0; i < len; i++) {
			css.href = s(arguments[i]);
			head.appendChild(css);
		}
	},
	
	loader : function(path, callback) {
		if($LAB === undefined || path === undefined || !path) {
			return;
		}

		/*
		function getFileExt(filename){
			var filearr = filename.split('.');
			return filearr[filearr.length - 1];
		}
		*/
		
		//var fileExt = getFileExt(path[i]);


		if(path[0] === undefined) {
			return $LAB.script( s(path) ).wait(callback);
		}

		for(var i in path) {
			path[i] = s(path[i]);
		}
		return $LAB.script(path).wait(callback);
	},

	template : function(template, replace){
		template = template.replace(/{[^{}]+}/g, function(key){
			return replace[key.replace(/[{}]+/g, "")] || "";
		});
		return template;
	},

	parseUri : function(url){
		function parseUri (str) {
			var	o   = parseUri.options,
				m   = o.parser[o.strictMode ? "strict" : "loose"].exec(str),
				uri = {},
				i   = 14;

			while (i--) uri[o.key[i]] = m[i] || "";

			uri[o.q.name] = {};
			uri[o.key[12]].replace(o.q.parser, function ($0, $1, $2) {
				if ($1) uri[o.q.name][$1] = $2;
			});

			return uri;
		};

		parseUri.options = {
			strictMode: false,
			key: ["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"],
			q:   {
				name:   "queryKey",
				parser: /(?:^|&)([^&=]*)=?([^&]*)/g
			},
			parser: {
				strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,
				loose:  /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/
			}
		};

		return url ? parseUri(url) : parseUri(window.location.href);
	},

	/**
	 * The Easthv Javascript Core File
	 *
	 *
	 * @author     XuQian(AlloVince) <xuqian@easthv.com>
	 * @copyright  2010 AlloVince
	 * @version    1.10
	 */
	ui : {

		config : {
			pathJqueryUi : ["/javascripts/jquery/jquery-ui.js", "/javascripts/jquery/jquery-ui-i18n.js", "/javascripts/jquery/jquery-ui-custom.js"],
			pathCodeMirror : ["/javascripts/codemirror/lib/codemirror.js"],
			pathSwfUploader : ["/javascripts/jquery/jquery.swfupload.js", "/javascripts/swfupload/swfupload.js", "/javascripts/swfupload/swfupload.queue.js"],
			pathTinymce : "/javascripts/jquery/jquery.tinymce.js"
		},

		_itemClass : {
			accordion : '.accordion',
			button : '.btn',
			buttonset : '.buttonset',
			progressbar : '.progressbar',
			dialog : '.dialog',
			panel : '.panel',
			tabs : '.tabs',
			grid : '.grid',
			datepicker : '.datepicker',
			codeeditor : '.codeeditor',
			swfuploader : '.swfuploader',
			htmleditor : '.htmleditor'
		},

		_getOption : function(item, setting) {
			var option = setting ? setting : {};
			var innerOption = $(item).attr("data-ui");
			setting = innerOption === undefined ? {} : $.parseJSON(innerOption);
			for(var i in setting) {
				option[i] = setting[i];
			}
			return option;
		},

		callback : function(item){
			 var option = eva.ui._getOption(item);
			 if(!option || option.callback === undefined || !option.callback) {
				 return false;
			 }
			 try {
				 eval(option.callback + '(item)');
			 } catch(err){
				 p(err);
			 }
		},

		initAccordion : function(setting){
			$(this._itemClass.accordion).each(function(){
				var option = eva.ui._getOption(this, setting);
				$(this).accordion(option);
				eva.ui.callback(this);
			});						
		},

		initButton : function(setting) {
			$(this._itemClass.button).each(function(){
				$(this).button(eva.ui._getOption(this, setting));
			});					 
		},

		initButtonset : function(setting){
			$(this._itemClass.buttonset).each(function(){
				$(this).buttonset(eva.ui._getOption(this, setting));
			});						
		},

		initDialog : function(setting){
			$(this._itemClass.dialog).each(function(){
				$(this).dialog(eva.ui._getOption(this, setting));
			});	

			$(".dialog_handler").click(function(){
				var dialog = $(this).attr("data-rel");
				if(dialog === undefined) {
					return false;
				}
				$(dialog).dialog("open");
			});
		},

		initTabs : function(setting){
			$(this._itemClass.tabs).each(function(){
				$(this).tabs(eva.ui._getOption(this, setting));
			});						
		},

		initProgressbar : function(setting){
			$(this._itemClass.progressbar).each(function(){
				$(this).progressbar(eva.ui._getOption(this, setting));
			});						
		},

		initDatepicker : function(setting){
			$(this._itemClass.datepicker).each(function(){
				$(this).datepicker(eva.ui._getOption(this, setting));
			});						
		},

		//beta
		initPanel : function(setting){
			$(this._itemClass.panel).each(function(){
				$(this).panel(eva.ui._getOption(this, setting));
			});						
		},

		//beta
		initGrid : function(setting) {
			var getWidth = function(td){
				var className = jQuery(td).prop("className");
				return parseInt(className.replace(/(.*)width_(\d+)(.*)/,"$2"));		
			}

			$(this._itemClass.grid).each(function(){
				$(this).grid(eva.ui._getOption(this), setting);

				$(" td, th", this).each(function(){
					var width = getWidth(this);
					if(width > 0) {
						jQuery(this).attr("width",width).css("width",width);
					}		
				});

			});	
		},

		//beta
		initHtmleditor : function(setting) {
			if(!$(this._itemClass.htmleditor)[0]) {
				return false;
			}

			var mceGlobelConfig = {
				mode : "exact",
				theme : "simple",
				skin_variant : "silver",
				//use absolute url
				relative_urls : false,
				//plugins :"autosave,contextmenu,fullscreen,inlinepopups,insertdatetime,save,searchreplace,safari,preview,style,layer,table,spellchecker,media",
				
				plugins : "autolink,lists,spellchecker,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template",
				theme_advanced_buttons1 : "save,newdocument,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,styleselect,formatselect,fontselect,fontsizeselect",
				theme_advanced_buttons2 : "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,cleanup,code,|,insertdate,inserttime,preview,|,forecolor,backcolor",
				theme_advanced_buttons3 : "tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,emotions,iespell,media,advhr,|,print,|,ltr,rtl,|,fullscreen",
				theme_advanced_buttons4 : "insertlayer,moveforward,movebackward,absolute,|,styleprops,spellchecker,|,cite,abbr,acronym,del,ins,attribs,|,visualchars,nonbreaking,template,blockquote,pagebreak,|,insertfile,insertimage",


				theme_advanced_toolbar_location : "top",
				theme_advanced_toolbar_align : "left",
				theme_advanced_statusbar_location : "bottom",
				theme_advanced_resizing : true,
				remove_linebreaks : false,
				extended_valid_elements : "pre[cols|rows|disabled|name|readonly|class]",
				script_url : s('/javascripts/tiny_mce/tiny_mce.js'),
				//script_url : '/javascripts/tiny_mce/tiny_mce_gzip.php',
				content_css: s("/skins/eva/reset_admin.css"),
				spellchecker_rpc_url : s('/javascripts/tiny_mce/plugins/spellchecker/rpc.php')
			}

			eva.loader(eva.ui.config.pathTinymce, function(){
				$(eva.ui._itemClass.htmleditor).each(function(){
					var opt = eva.ui._getOption(this);
					var mceconfig = mceGlobelConfig;
					if(opt) {
						for(var i in opt){
							mceconfig[i] = opt[i];
						}
					}
					mceconfig.editor_selector = this;
					$(this).width("100%").tinymce(mceconfig);
				});				
			});
		},

		initCodeeditor : function(){
			if(!$(this._itemClass.codeeditor)[0]) {
				return false;
			}

			var modeMapping = {
				'htmlmixed' : ['xml', 'css', 'javascript'],
				'php' : ['xml', 'css', 'clike', 'javascript']
			}

			eva.loadcss('/javascripts/codemirror/lib/codemirror.css');

			eva.loader(eva.ui.config.pathCodeMirror, function(){
				$(eva.ui._itemClass.codeeditor).each(function(){
					var opt = eva.ui._getOption(this);
					var mode = opt.mode;
					if(!mode) {
						return false;
					}

					//load theme
					var theme = opt.theme ? opt.theme : 'default';
					eva.loadcss('/javascripts/codemirror/theme/' + theme + '.css');

					var modePath = [s("/javascripts/codemirror/mode/" + mode + "/" + mode + ".js")];
					if(modeMapping[mode]) {
						for(var i in modeMapping[mode]) {
							modePath.push(s("/javascripts/codemirror/mode/" + modeMapping[mode][i] + "/" + modeMapping[mode][i] + ".js"));
						}
					}
					 
					var textarea = this;
					eva.loader(modePath, function(){
						CodeMirror.fromTextArea(textarea, opt);						
					});

				});
			});						 
		},

		//beta
		initSwfuploader : function(){
			if(!$(this._itemClass.swfuploader)[0]) {
				return false;
			}

			var defaultOpt = {
				upload_url: d("/files"),
				file_size_limit : "10240",
				file_types : "*.*",
				file_types_description : "All Files",
				file_upload_limit : "10",
				flash_url : s("/javascripts/swfupload/swfupload.swf"),
				flash9_url : s("/javascripts/swfupload/swfupload_fp9.swf"),
				button_image_url : s( '/javascripts/swfupload/button_en.png'),
				button_width : 61,
				button_height : 22,
				debug: false
			}

			function getCookie( name ) {
				var start = document.cookie.indexOf( name + "=" );
				var len = start + name.length + 1;
				if ( ( !start ) && ( name != document.cookie.substring( 0, name.length ) ) ) {
					return null;
				}
				if ( start == -1 ) return null;
				var end = document.cookie.indexOf( ';', len );
				if ( end == -1 ) end = document.cookie.length;
				return unescape( document.cookie.substring( len, end ) );
			}


			eva.loader(eva.ui.config.pathSwfUploader, function(){
				$(eva.ui._itemClass.swfuploader).each(function(){
					var opt = eva.ui._getOption(this);
					var optCurrent = defaultOpt;
					for(var i in opt) {
						optCurrent[i] = opt[i];
					}

					optCurrent.button_placeholder = this;
					if(!optCurrent.file_post_name) {
						optCurrent.file_post_name = $(this).attr("name");
					}

					var sessionId = getCookie("PHPSESSID");

					if(sessionId) {
						optCurrent.post_params = {"PHPSESSID" : sessionId};
					}
					$(this).swfupload(optCurrent);
				});
			});	
		},

		_inited : false,

		_init : function(){
			for(var func in eva.ui._itemClass) {
				func = 'init' + func.charAt(0).toUpperCase() + func.substr(1);
				if(eva.ui[func]){
					eva.ui[func]();
				}
			}	
		},

		init : function(){
			if(false === this._inited) {
				eva.loader(this.config.pathJqueryUi, this._init);
				this._inited = true;
			}
		}
	}
};

})();



-->
